///////////////////////////////////////////////////////////////////////////////
//                                                                             
//  Copyright (C) 2024  ZengZong (USB-DATA) <472934453@qq.com>     
//
///////////////////////////////////////////////////////////////////////////////
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <cstring>
#include <termios.h>
#include <stdlib.h>

int open_serial_port(const char *device);
void configure_serial_port(int fd, int baud_rate);
ssize_t read_from_serial_port(int fd, void *buf, size_t nbytes);
void close_serial_port(int fd);
void write_from_serial_port(char* writebuf,int fd);
void tomain(char* writebuf);

void tomain(char* writebuf)
{
    const char *device = "/dev/ttyUSB0";
    int baud_rate = B9600;
    int fd = open_serial_port(device);
    if (fd == -1) exit(1);
    configure_serial_port(fd, baud_rate);
    char buffer[256];
    ssize_t n = read_from_serial_port(fd, buffer, sizeof(buffer));
    if (n > 0) {
        buffer[n] ;
        printf("Read %zd bytes: %sn", n, buffer);
    } else {
        printf("No data read from serial portn");
    }
    
    write_from_serial_port(writebuf, fd);   
    
     
    close_serial_port(fd);
}

// int main() {
//     const char *device = "/dev/ttyUSB0";
//     int baud_rate = B9600;
//     int fd = open_serial_port(device);
//     if (fd == -1) return 1;
//     configure_serial_port(fd, baud_rate);
//     char buffer[256];
//     ssize_t n = read_from_serial_port(fd, buffer, sizeof(buffer));
//     if (n > 0) {
//         buffer[n] ;
//         printf("Read %zd bytes: %sn", n, buffer);
//     } else {
//         printf("No data read from serial portn");
//     }
// 	// char writebuf[]="HELLO!!!";
// 	while(1){
// 		char writebuf[]="";
// 		scanf("%s",writebuf);
// 	    write_from_serial_port(writebuf, fd);   
// 	}
	 
//     close_serial_port(fd);
//     return 0;
// }
void write_from_serial_port(char* writebuf,int fd){
    write(fd,writebuf, strlen(writebuf)); 
}
int open_serial_port(const char *device) {
    int fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd == -1) {
        perror("Unable to open serial port");
    } else {
        fcntl(fd, F_SETFL, 0);
    }
    return fd;
}
void configure_serial_port(int fd, int baud_rate) {
    struct termios options;
    tcgetattr(fd, &options);
    cfsetispeed(&options, baud_rate);
    cfsetospeed(&options, baud_rate);
    options.c_cflag |= (CLOCAL | CREAD);
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    tcsetattr(fd, TCSANOW, &options);
}
ssize_t read_from_serial_port(int fd, void *buf, size_t nbytes) {
    return read(fd, buf, nbytes);
}
void close_serial_port(int fd) {
    close(fd);
}